package core.proto;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.Highlighter;

public class DocumentSearchBar extends JPanel
{
    private static final long serialVersionUID = 1L;
    public JButton close;
    public JTextField search = new JTextField(15);
    public PaintDoc doc;

    public DocumentSearchBar(final PaintDoc doc) {
        this.doc=doc;
        close= new JButton(new ImageIcon( this.getClass().getResource("/img/close.png" ) ));
        close.addActionListener( new ActionListener(){
            @Override
            public void actionPerformed( ActionEvent arg0 ) {
                search.setText( "" );
                AllComponents.removeHighlights( doc );
                AllComponents.sp2.repaint();
            }
            
        });
        search.addActionListener( new SearchHandler() );
        setSize(700, 60);
        JPanel inside= new JPanel(new FlowLayout());
        inside.setVisible( true );
        inside.setSize( 100, 60 );
        inside.add( search );
        inside.add( close );
        setLayout(new BorderLayout());
        add(inside, BorderLayout.LINE_END);
        setVisible(true);
    }


    private class SearchHandler implements ActionListener{

        public void actionPerformed( ActionEvent arg0 ) {
            String term= search.getText();
            searchDoc( term);
        }

    }

    public void searchDoc(String term) {

        Highlighter.HighlightPainter myHighlightPainter = new TextHighlighter(
                Color.lightGray);

        // highlight the text that is displayed on screen currently
        term = term.toLowerCase();
        try {
            Highlighter hilite;
            Document docum;
            hilite = doc.getHighlighter();
            docum = doc.getDocument();

            String text = docum.getText(0, docum.getLength());
            text = text.toLowerCase();
            int pos = 0;
            int temPos = -1;
            // Search for pattern
            while ((pos = text.indexOf(term, pos)) >= 0) {
                // Create highlighter using private painter and apply around
                // pattern
                hilite.addHighlight(pos, pos + term.length(),
                        myHighlightPainter);
                temPos = pos;
                pos += term.length();
            }
            doc.modelToView(temPos);
            doc.repaint();
            AllComponents.sp2.repaint();



        } catch (BadLocationException e) {
            System.out.println("WARN: error while highlighting...");
            // throw new CollabVizException(e);
        }
    }
}
